#include "UapStateConnectPend.h"
#include "UapStateMap.h"
#include "ClientUapProxy.h"
#include "common.pb.h"
#include "UAP.pb.h"
#include "list"
#include "MediaLibrary.h"
#include "Trace.h"

namespace tsc
{
namespace sgw
{

using namespace UserApplicationPart;
using namespace ProtocolsCommon;
using namespace tsc::common;

/*******************************************************************************
 *
 * Constructor
 *
 ******************************************************************************/
UapStateConnectPend::UapStateConnectPend() :
	UapStateBase("ConnectPend")
{

} // UapStateConnectPend::UapStateConnectPend

/*******************************************************************************
 *
 * Destructor
 *
 ******************************************************************************/
UapStateConnectPend::~UapStateConnectPend()
{

} // UapStateConnectPend::~UapStateConnectPend

//===================================================================
UapStateConnectPend* UapStateConnectPend::instance()
{
	static UapStateConnectPend mInstance;
	return &mInstance;
}

//===================================================================
void
UapStateConnectPend::handleEventUapConnectionReq(
    UapGenerator* uapGen,
    UapEventConnectionReq* event,
    EventData*& eventData)
{
	// store data specific for generator
	uapGen->setCapabilities(event->getClientCapabilities());

	// store data specific for client in the context
	uapGen->getContext()->setClientIpAddress(event->getClientIpAddress());
	uapGen->getContext()->setClientUapPort(event->getClientUapPort());

	// store mapping between generatorId(connectionId) and socketId
	ClientUapProxy::instance().addConnIdMapping(
	        uapGen->getConnectionId(),
	        event->getSocketConnId());

	//=====================================
	// Send response
	//=====================================
	if(!ClientUapProxy::instance().sendUapConnectionCfm(*uapGen))
	{
		TRACE(1, STR("Failed to send UapConnectionCfm, deleting generator"));
	    delete uapGen;
	    uapGen = 0;
	}
	else
	{
	    TRACE(4, STR("UapConnectionCfm sent, connId=0x%x", uapGen->getConnectionId()));
		uapGen->changeState(UapStateMap::mStateConnected);
	}

    EventData::deleteEvent(eventData);
}

//===================================================================
void
UapStateConnectPend::handleEventUapConnectionReleaseReq(
    UapGenerator* uapGen,
    UapEventConnectionReleaseReq* event,
    EventData*& eventData)
{
    TRACE(4, STR("Received UapConnectionRelease during connection establishment"));

    delete uapGen;
    uapGen = 0;

    EventData::deleteEvent(eventData);
}

} // namespace sgw
} // namespace tsc
